from flaskAdminApp import db, app
from datetime import datetime
import time
from itsdangerous import TimedJSONWebSignatureSerializer as Serializer
from werkzeug.security import generate_password_hash, check_password_hash


class sys_user(db.Model):
    # 系统用户表
    __tablename__ = 'sys_user'
    user_id = db.Column(db.Integer, primary_key=True, comment='用户id', autoincrement=True)
    dept_id = db.Column(db.Integer, comment='部门id', default=0)
    user_name = db.Column(db.String(30), comment='用户名')
    nick_name = db.Column(db.String(30), comment='昵称')
    email = db.Column(db.String(50), comment='邮箱')
    phonenumber = db.Column(db.Integer(), comment='手机号')
    _password = db.Column('password', db.String(100), comment='密码')
    create_time = db.Column(db.DateTime, default=datetime.now, index=True, comment='创建时间')
    update_time = db.Column(db.DateTime, default=datetime.now, index=True, comment='更新时间')
    create_by = db.Column(db.String(64), comment='创建人', default=0)

    @property
    def password(self):
        return self._password

    @password.setter
    def password(self, rawpwd):
        self._password = generate_password_hash(rawpwd)

    def check_password(self, rawpwd):
        return check_password_hash(self._password, rawpwd)

    def to_json(self):
        dicts = self.__dict__
        dicts['create_time'] = dicts['create_time'].strftime("%Y-%m-%d %H:%M:%S")
        dicts['update_time'] = dicts['update_time'].strftime("%Y-%m-%d %H:%M:%S")
        if "_sa_instance_state" in dicts:
            del dicts["_sa_instance_state"]
        if "_password" in dicts:
            del dicts["_password"]
        return dicts

    @staticmethod
    def create_token(id):
        s = Serializer(app.config['SECRET_KEY'], expires_in=1800)
        token = s.dumps({"user_id": id}).decode('ascii')
        return token


class sys_dept(db.Model):
    # 部门表
    __tablename__ = "sys_dept"
    dept_id = db.Column(db.Integer, autoincrement=True, primary_key=True, comment='部门id')
    parent_id = db.Column(db.Integer, default=0, comment='父级ID')
    dept_name = db.Column(db.String(30), comment='部门名称')
    create_time = db.Column(db.DateTime, default=datetime.now, index=True, comment='创建时间')
    update_time = db.Column(db.DateTime, default=datetime.now, index=True, comment='更新时间')
    create_by = db.Column(db.String(64), comment='创建人')

    def to_json(self):
        dicts = self.__dict__
        dicts['create_time'] = dicts['create_time'].strftime("%Y-%m-%d %H:%M:%S")
        dicts['update_time'] = dicts['update_time'].strftime("%Y-%m-%d %H:%M:%S")
        if "_sa_instance_state" in dicts:
            del dicts["_sa_instance_state"]
        return dicts
